<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar :page-no="78" :has-qr="true" :qr-active="qrActive" :add-active="addActive" :del-active="delActive"
        :edit-active="editActive" :cancel-active="cancelActive" :save-active="saveActive" :has-edit="false"
        :has-save="false" @add="add" @cancel="cancel" @edit="edit" @del="del" @save="save('formData')" />
    </template>
    <template v-slot:search-box>
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="search()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">检验类型名称</div>
            <el-input v-model="checkTypeName" placeholder="请输入检验类型名称" clearable />
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:table-box>
      <el-table ref="tableData" v-loading="loading" :data="tableData" stripe border height="88%" @row-click="handleEdit"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="checkTypeName" label="检验类型名称" />
        <el-table-column prop="checkTypeListName" label="检验类型标识" />
        <el-table-column label="操作" width="200">
          <template v-if="scope.row.checkTypeId" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" v-if="judgePermission(79, 'edit')" size="small" @click="edit">
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small" v-if="judgePermission(79, 'delete')"
              @click="handleDelete(scope.row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
        @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
    </template>
    <template v-slot:dialog>
      <el-dialog :title="titleText + '检验类型信息'" :visible.sync="dialogFormVisible" :before-close="cancel">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <el-form-item label="检验类型名称 :" prop="checkTypeName" class="w50p">
            <el-input v-model="formData.checkTypeName" placeholder="请输入检验类型名称" clearable />
          </el-form-item>
          <el-form-item label="检验类型标识:" prop="breedTypeList" class="w50p">
            <el-select filterable clearable v-model="formData.breedTypeList" multiple allow-create default-first-option clearable>
              <el-option v-for="item in enumList" :key="item.breedTypeNo" :label="item.breedTypeName"
                :value="item.breedTypeNo" />
            </el-select>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel('formData')">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import vueQr from "vue-qr";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

import DetectionTypeApi from "@/api/inspection-management/detection-type-management";
import BreedingTypeApi from "@/api/basic-info-manage/breeding-type-manage";
export default {
  name: "PatrolPoineManage",
  components: {
    ActionBar,
    Pagination,
    vueQr,
    BaseMainSlot
    // SearchBox
    // SeeEquip
  },
  mixins: [mymixin],
  data() {
    var validateInspectionPointCode = (rule, value, callback) => {
      setTimeout(() => {
        if (!value) {
          callback(new Error("编号不能为空！！！"));
        } else {
          var patrn = /[`~!@#$%^&*()\+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）={}|《》？：“”【】、；‘'，。、]/im;
          if (patrn.test(value)) {
            callback(new Error("编号不能包含 $、&、￥等特殊字符"));
            // 如果包含特殊字符返回false
          } else {
            callback();
          }
        }
      }, 20);
    };
    return {
      obj: {
        name: ""
      },
      qrActive: false,
      // 巡检点名称
      checkTypeName: "",
      enumList: [],
      rules: {
        checkTypeName: [
          { required: true, message: "请输入检验类型名称", trigger: "blur" }
        ],
        breedTypeList: [
          { required: true, message: "请输入检验类型标识", trigger: "blur" }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false,
      facilityVOList: [],
      isShowEquip: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    // 动态添加数据
    formData: {
      deep: true,
      handler(val) {
        if (val.latitude || val.longitude) {
          this.center = {
            lng: val.longitude,
            lat: val.latitude
          };
        }
      }
    }
  },
  created() { },
  mounted() {
    this.search();
    this.queryEnum();
  },
  methods: {
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          checkTypeName: this.checkTypeName || undefined
        }
      };
      DetectionTypeApi.queryPageByCondition(params).then(res => {
        this.loading = false;
        let data = res.data;
        data.content.forEach(el => {
          el['checkTypeListName'] = this.getCheckTypeListName(el.checkTypeListStr)
        });
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
        }
        // 赋值数组
        this.tableData = [];
        if (data !== undefined) this.tableData = data.content;
        console.log(this.tableData)
        this.addblankmet();
        this.resetActionBar();
      });
    },
    queryEnum() {
      BreedingTypeApi.queryByCondition().then(res => {
        this.enumList = res.data;
        this.tableData.forEach(el => {
          el['checkTypeListName'] = this.getCheckTypeListName(el.checkTypeListStr)
        });
      });
    },
    getCheckTypeListName(typeList) {
      let checkTypeListName = []
      this.enumList = this.enumList ? this.enumList : []
      this.enumList.forEach(el => {
        if (typeList && typeList.indexOf(el.breedTypeNo) !== -1) {
          checkTypeListName.push(el.breedTypeName)
        }
      })
      return checkTypeListName.join(',')
    },
    seeEquip(row) {
      // console.log("a");
      this.facilityVOList = row.facilityVOList;
      this.isShowEquip = true;
      // console.log(this.isShowEquip);
      // console.log(row.facilityVOList);
    },
    handleEdit(row) {
      // TODO 点击行元素后 edit
      this.facilityList = [];
      this.nowfishPondId = "";
      if (row.checkTypeId) {
        this.formData = JSON.parse(JSON.stringify(row));
        this.formData['breedTypeList'] = row.checkTypeListStr.split(',');
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
        this.canInput = false;
        this.qrActive = true;
      } else {
        this.formData = {};
        this.qrActive = false;
      }
    },
    handleSelectionChange(list) {
      this.inspectionPointIdList = [];
      this.inspectionPointIdList = list.map(item => item.checkTypeId);
      if (this.inspectionPointIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      DetectionTypeApi.delListById({
        idList: [this.inspectionPointIdList]
      }).then(res => {
        if (res.success) {
          this.search();
          this.$message.success(res.message || "删除成功");
        } else {
          this.$message.warning(res.message || "删除失败");
        }
      });
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          DetectionTypeApi.delById({ id: row.checkTypeId }).then(res => {
            if (res.success) {
              this.search();
              this.resetActionBar()
              this.$message.success(res.message || "删除成功");
            } else {
              this.resetActionBar()
              this.$message.warning(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.resetActionBar()
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            DetectionTypeApi.edit(this.formData).then(res => {
              if (res.success) {
                this.search();
                this.$message.success(res.message || "修改成功！");
              } else {
                this.$message.error(res.message || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            DetectionTypeApi.add(this.formData).then(res => {
              if (res.success) {
                this.search();
                this.$message.success(res.message || "新增成功！");
              } else {
                this.$message.error(res.message || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .el-form-item__label {
  min-width: 155px !important;
}

::v-deep .content {
  .table-box {
    width: 50% !important;
  }

  .form {
    width: 48% !important;
    position: relative;
    overflow: hidden;
  }
}

::v-deep .lng {
  .el-form-item__content {
    >span {
      width: 100%;
    }
  }

  .el-input__inner {
    min-width: 90px;
  }
}

::v-deep .lat {
  .el-form-item__content {
    >span {
      width: 100%;
    }
  }

  .el-form-item__label {
    text-align: end;
    min-width: 100px !important;
  }
}

.qrCode {
  text-align: center;
}

.map {
  position: absolute;
  bottom: 0px;
  left: 0;
  width: 100%;
  height: 66%;
  touch-action: none;
}

.noClick {
  cursor: not-allowed;
}

.df {
  display: flex;
  align-items: center;
  width: 100%;

  // 多选
  i {
    font-size: 30px;
    margin-left: 10px;
    cursor: pointer;
  }
}

.dfs {
  ::v-deep .el-form-item__content {
    display: flex;
    /*flex-direction: column;*/
    flex-wrap: wrap;
    flex-direction: row;
    height: 120px;
    overflow-y: hidden;
  }
}

.tags {
  width: 100%;
  height: 90px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;

  .tag-item {
    height: 30px;
    padding: 5px 10px;
    background-color: #00a1c2;
    border-radius: 8px;
    display: flex;
    align-items: center;
    margin-top: 10px;
    margin-right: 10px;

    i {
      font-size: 14px;
    }
  }
}

::v-deep .dialog {
  .el-dialog__headerbtn {
    top: 0;
    right: 10px;
  }

  // .el-dialog {
  //   margin-top: 10vh !important;
  //   min-width: 15%;
  //   width: 200px !important;
  //   height: auto !important;
  // }
}
</style>
